#ifdef _WIN32
#pragma comment(lib, "ws2_32.lib")
#endif

#include <winsock2.h>
#include <stdio.h>
#include <string.h>

#define BUFF_LENGTH 1024

int main()
{
    // 初始化Windows套接字环境
    WSADATA wsa_Data;
    WSAStartup(MAKEWORD(2, 2), &wsa_Data);

    // 创建客户端套接字
    SOCKET client_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (client_socket == INVALID_SOCKET)
    {
        printf("Failed to create socket\n");
        WSACleanup();
        return 1;
    }

    // 配置服务器地址结构体
    struct sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(8080);
    server_addr.sin_addr.s_addr = inet_addr("192.168.137.1");

    // 连接到服务器
    if (connect(client_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) == SOCKET_ERROR)
    {
        printf("Failed to connect to server\n");
        closesocket(client_socket);
        WSACleanup();
        return 1;
    }

    printf("Successfully connected to server!\n");

    char buffer[BUFF_LENGTH];
    char recv_buffer[BUFF_LENGTH];
    int recv_len;

    // 主循环：从控制台读取输入并发送到服务器
    while (1)
    {
        printf("Please enter message to send (type 'exit' to quit): ");
        fgets(buffer, BUFF_LENGTH, stdin);

        // 移除换行符
        buffer[strcspn(buffer, "\n")] = 0;

        // 检查是否退出
        if (strcmp(buffer, "exit") == 0)
        {
            break;
        }

        // 发送消息到服务器
        if (send(client_socket, buffer, strlen(buffer), 0) == SOCKET_ERROR)
        {
            printf("Send failed\n");
            break;
        }

        // 接收服务器的回显
        recv_len = recv(client_socket, recv_buffer, BUFF_LENGTH, 0);
        if (recv_len > 0)
        {
            recv_buffer[recv_len] = '\0';
            printf("Server echo: %s\n", recv_buffer);
        }
        else if (recv_len == 0)
        {
            printf("Server closed the connection\n");
            break;
        }
        else
        {
            printf("Receive failed\n");
            break;
        }
    }

    // 关闭套接字并清理
    closesocket(client_socket);
    WSACleanup();
    return 0;
}